package sample.spring.ibatis.controller;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.pojomatic.Pojomatic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sample.spring.ibatis.model.Customer;
import sample.spring.ibatis.service.ICustomerService;

@RestController
@RequestMapping(value = "/customerService")
public class CustomerController {

    @Autowired
    ICustomerService customerService;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Customer getCustomer(@PathVariable("id") Integer id) {
        ValueOperations<String, Customer> ops = redisTemplate.opsForValue();
//        if(!redisTemplate.hasKey("1111")) {
            redisTemplate.opsForHash().put("customer", id.toString(), JSON.toJSONString(customerService.getCustomer(id)));
//            ops.set("1111", customerService.getCustomer(id));
//        }else{
//            Customer customer = ops.get("1111");
            String json= (String) redisTemplate.opsForHash().get("customer",id.toString());
            Customer customer = JSON.parseObject(json,new TypeReference<Customer>() {}) ;
            System.out.println("customer is   -------- "+customer);

//        }
        return customerService.getCustomer(id);
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<Customer> getAllCustomer() {
        return customerService.getAllCustomer();
    }

    @RequestMapping(method = RequestMethod.POST)
    public Customer saveCustomer() {
        Customer customer = new Customer();
        customer.setFirstName("1");
        customer.setLastName("1");
        customer.setMobileNo("1111");
        return customerService.saveCustomer(customer);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteCustomersById(@PathVariable("id") Integer id) {
        customerService.deleteCustomersById(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public void updateCustomersById(@PathVariable("id") Integer id, Customer customer) {
        customerService.updateCustomer(customer);
    }

}
